import { LockOutlined, MailOutlined, UserOutlined, } from '@ant-design/icons';
import { Alert, } from 'antd';
import React, { useState, useEffect } from 'react';
import ProForm, { ProFormCaptcha, ProFormText } from '@ant-design/pro-form';
import { connect,  } from 'umi';
import styles from './index.less';

const Login = (props) => {
  const { userLogin = {}, submitting, dispatch } = props;
  const { status,  captcha } = userLogin;

  useEffect(() => {
    dispatch({ type: 'login/captchaEffects' });
  }, []);

  const handleSubmit = (values) => {
    dispatch({
      type: 'login/loginEffects',
      payload: { ...values, ...{deviceId: captcha.deviceId} },
    });
  };

  return (
    <div className={styles.main}>
      <ProForm
        initialValues={{
          autoLogin: true,
        }}
        submitter={{
          render: (_, dom) => dom.pop(),
          submitButtonProps: {
            loading: submitting, size: 'large',
            style: { width: '100%', },
          },
        }}
        onFinish={(values) => {
          handleSubmit(values);
          return Promise.resolve();
        }}
      >

        {!status.success && !submitting && (<Alert style={{ marginBottom: 24, }} message={status.msg} type="error" showIcon /> )}

        <ProFormText
          name="username"
          fieldProps={{ size: 'large', prefix: <UserOutlined className={styles.prefixIcon} />, }}
          placeholder={'请输入登录名称'}
          rules={[ { required: true,  message: "请输入登录名称!", }, ]}
        />
        <ProFormText.Password
          name="password"
          fieldProps={{ size: 'large', prefix: <LockOutlined className={styles.prefixIcon} />, }}
          placeholder={'请输入登录密码'}
          rules={[ { required: true, message: "请输入登录密码！", }, ]}
        />

        <div className={styles.captcha}>
          <ProFormCaptcha
            fieldProps={{ size: 'large', prefix: <MailOutlined className={styles.prefixIcon} />, }}
            captchaProps={{ size: 'large', }}
            placeholder={'请输入验证码'}
            captchaTextRender={ (timing, count) => {
              return (<img src={captcha.content} />);
            }}
            name="code"
            countDown={1}
            rules={[ { required: true, message: "请输入验证码！", }, ]}
            onGetCaptcha={async (mobile) => {
              dispatch({ type: 'login/captchaEffects' });
              return;
            }}
          />
        </div>
      </ProForm>
    </div>
  );
};

export default connect(({ login, loading }) => ({
  userLogin: login,
  submitting: loading.effects['login/loginEffects'],
}))(Login);
